package me.work.pay.jsyl.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.chaomeng.a8sdklibrary.bluetooth.BLEManager;
import com.blankj.utilcode.util.ScreenUtils;
import com.chaomeng.a8sdklibrary.event.WifiInfoEvent;
import com.chaomeng.a8sdklibrary.utils.LogUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import me.work.pay.jsyl.R;
import me.work.pay.jsyl.app.Constants;
import me.work.pay.jsyl.app.utils.SBLEManager;
import me.work.pay.jsyl.di.component.DaggerWifiComponent;
import me.work.pay.jsyl.mvp.contract.WifiContract;
import me.work.pay.jsyl.mvp.model.AppModel;
import me.work.pay.jsyl.mvp.presenter.WifiPresenter;
import me.work.pay.jsyl.mvp.ui.adapter.MyBroadcastReceiver;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 09/23/2020 16:47
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class WifiLandActivity extends BaseActivity<WifiPresenter> implements WifiContract.View {

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerWifiComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    public static WifiLandActivity main;


    @Override
    public void onAttachedToWindow() {

        super.onAttachedToWindow();
    }


    @Override
    public int initView(@Nullable Bundle savedInstanceState) {

        return R.layout.activity_wifi_land; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.activity_wifi_land);
    }
    private void init_page() {
        SPUtils.getInstance().put(Constants.sp_page_value, "5");
    }

    MyBroadcastReceiver wifiReceiver;

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        main = this;
        init_page();
    }// 重写MTU

    @Override
    protected void onResume() {
        super.onResume();
        init_page();
        SBLEManager.getDefault().initBlueTooth(this);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SBLEManager.getDefault().registerReceiver();
            }
        }, 4000);//3秒后执行Runnable中的run方法
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        wifiReceiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        registerReceiver(wifiReceiver, filter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private String mSsid = null;
    private String mPswd = null;
    private String mBssid = null;
    WifiManager wifiManager;

    /**
     * wifi设置
     *
     * @param ssid
     * @param pws
     */
    private WifiConfiguration getWifiConfig(String ssid, String pws) {
        LogUtil.i("ArmsHttpLog", ssid + "到这里了吗？？？wifi密码：" + pws);

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = isExist(ssid);
        if (tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }
        LogUtil.i("ArmsHttpLog", ssid + "wifi密码：" + pws);
        if (!TextUtils.isEmpty(pws)) {
            LogUtil.i("ArmsHttpLog", "wifi密码：" + pws);
//            return setWifiParamsPassword(ssid, pws);
            config.preSharedKey = "\"" + pws + "\"";
            config.hiddenSSID = true;

            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        return config;
    }

    /**
     * 得到配置好的网络连接
     *
     * @param ssid
     * @return
     */
    private WifiConfiguration isExist(String ssid) {
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\"" + ssid + "\"")) {
                return config;
            }
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWifiInfoEvent(WifiInfoEvent event) {
        if (event != null) {
            if (event.ssid != null) {
                mSsid = event.ssid;
                mPswd = event.pswd;
                mBssid = event.bssid;
                LogUtil.i("CM", "WifiInfoEvent : " + mPswd + "    " + mSsid + "    " + mBssid);
//
                WifiInfo info = wifiManager.getConnectionInfo();
                wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
                GroupListActivity.activity.soundMaker.makeSound("3", "26");//正在连接无线网络
                int netId = wifiManager.addNetwork(getWifiConfig(mSsid, mPswd));
                wifiManager.enableNetwork(netId, true);
            }
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GroupListActivity.activity.soundMaker.makeSound("3", "23");//退出配网模式
        unregisterReceiver(wifiReceiver);
        SBLEManager.getDefault().unregisterReceiver();
    }
}
